import { get } from '@ajax';

export default {
  namespace: 'commonTable',
  state: {
    tableUrl: '',
    tableRecords: [],
    tablePage: 1,
    tableSize: 10,
    tableTotal: 0,
    tableSearch: {},
  },
  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
    init() {
      return {
        tableUrl: '',
        tableRecords: [],
        tablePage: 1,
        tableSize: 10,
        tableTotal: 0,
        tableSearch: {},
      };
    },
  },
  effects: {
    * getTableList({ url }, { put, select }) {
      if (url) {
        yield put({
          type: 'save',
          payload: {
            tableUrl: url,
          },
        });
      }
      const { tableUrl, tablePage, tableSize, tableSearch } = yield select(s => ({ ...s['commonTable'] }));
      const res = yield get(url ? url : tableUrl, {
        pageNum: tablePage,
        pageSize: tableSize,
        ...tableSearch,
      });
      // console.log(res)
      if (res.success) {
        yield put({
          type: 'save',
          payload: {
            tableRecords: res.data,
            tableTotal: res.count,
          },
        });
      }
    },
    * search({ val }, { put, select }) {
      const { tableSearch } = yield select(s => ({ ...s['commonTable'] }));
      yield put({
        type: 'save',
        payload: {
          tableSearch: {
            ...tableSearch,
            ...val,
          },
          tablePage: 1,
        },
      });
      yield put({
        type: 'getTableList',
      });
    },
    * onPageChange({ page }, { put }) {
      // console.log(page)
      yield put({
        type: 'save',
        payload: {
          tablePage: page,
        },
      });
      yield put({
        type: 'getTableList',
      });
    },
    * onShowSizeChange({ size }, { put }) {
      // console.log(size)
      yield put({
        type: 'save',
        payload: {
          tablePage: 1,
          tableSize: size,
        },
      });
      yield put({
        type: 'getTableList',
      });
    },
  },
};
